package br.com.universidade.servlets.professor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.universidade.bean.Professor;
import br.com.universidade.dao.ProfessorDao;
import br.com.universidade.servlets.GenericServlet;

@WebServlet(urlPatterns="/pesquisarProfessor")
public class ListarProfessorServlet extends GenericServlet{
	private static final long serialVersionUID = 1L;
	private static final String LISTA_PROFESSORES= "listaProfessores";
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		try {
			listarProfessores(req);
			saveSucessMessage(req);
			redirect(req,resp);
		} catch (Exception e) {
			saveErrorMessage(req);
			e.printStackTrace();
		}
	}
	
	private void redirect(HttpServletRequest req, HttpServletResponse resp)throws Exception {
		req.getRequestDispatcher(JSP_LISTAR_PROFESSOR).forward(req, resp);
	}

	private void listarProfessores(HttpServletRequest req) throws Exception {
		ProfessorDao professorDao = new ProfessorDao();
		List<Professor> lista = professorDao.findAll(Professor.class);
		req.setAttribute(LISTA_PROFESSORES, lista);
	}
	
}